/**
 * Mock数据服务
 * 用于开发阶段的接口调试和功能测试
 */

import type { Tenant, User, Role, Permission } from '@/types/abp'

// 模拟延迟
const delay = (ms: number = 500) => new Promise(resolve => setTimeout(resolve, ms))

// 生成随机ID
const generateId = () => Math.random().toString(36).substr(2, 9)

// 生成随机数据
const generateRandomTenants = (count: number): Tenant[] => {
  const tenants: Tenant[] = []
  const tenantNames = ['Matrix科技', '创新企业', '数字集团', '智能公司', '云端科技']
  const tenantCodes = ['MATRIX', 'INNOVATE', 'DIGITAL', 'SMART', 'CLOUD']

  for (let i = 0; i < count; i++) {
    tenants.push({
      id: generateId(),
      name: tenantNames[i % tenantNames.length] + (i >= tenantNames.length ? i : ''),
      code: tenantCodes[i % tenantCodes.length] + (i >= tenantCodes.length ? i : ''),
      displayName: tenantNames[i % tenantNames.length] + (i >= tenantNames.length ? i : ''),
      description: `这是${tenantNames[i % tenantNames.length]}的描述信息`,
      isActive: Math.random() > 0.2,
      isDefault: i === 0,
      adminEmailAddress: `admin${i}@example.com`,
      databaseType: 'PostgreSQL',
      connectionString: 'Server=localhost;Port=5432;Database=matrix_db;',
      enabledFeatures: ['keycloakIntegration', 'fileStorage', 'aiAnalysis'],
      maxUsers: Math.floor(Math.random() * 1000) + 100,
      maxStorageGB: Math.floor(Math.random() * 100) + 10,
      maxApiCallsPerDay: Math.floor(Math.random() * 10000) + 1000,
      keycloakRealm: 'matrix-realm',
      keycloakRealmDisplayName: 'Matrix Realm',
      keycloakTheme: 'matrix',
      keycloakSettings: ['socialLogin', 'mfa'],
      timezone: 'Asia/Shanghai',
      customSettings: [],
      creationTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      lastModificationTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      userCount: Math.floor(Math.random() * 100) + 10,
      logo: null
    })
  }

  return tenants
}

const generateRandomUsers = (count: number): User[] => {
  const users: User[] = []
  const firstNames = ['张', '李', '王', '刘', '陈', '杨', '赵', '黄', '周', '吴']
  const lastNames = ['伟', '芳', '娜', '敏', '静', '丽', '强', '磊', '军', '洋']
  const roles = ['Admin', 'User', 'Manager', 'Developer']

  for (let i = 0; i < count; i++) {
    const firstName = firstNames[Math.floor(Math.random() * firstNames.length)]
    const lastName = lastNames[Math.floor(Math.random() * lastNames.length)]

    users.push({
      id: generateId(),
      userName: `user${i + 1}`,
      name: firstName,
      surname: lastName,
      email: `user${i + 1}@example.com`,
      phoneNumber: `138${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}`,
      isActive: Math.random() > 0.1,
      lockoutEnabled: Math.random() > 0.7,
      lockoutEnd: null,
      twoFactorEnabled: Math.random() > 0.8,
      lastLoginTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
      creationTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      lastModificationTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      roleNames: [roles[Math.floor(Math.random() * roles.length)]],
      grantedPermissions: ['Identity.Users.Read', 'Identity.Roles.Read'],
      tenantId: Math.random() > 0.3 ? generateId() : null,
      tenantName: Math.random() > 0.3 ? '示例租户' : null,
      avatar: null,
      gender: Math.random() > 0.5 ? 'male' : 'female',
      birthDate: new Date(1980 + Math.floor(Math.random() * 30), Math.floor(Math.random() * 12) + 1, Math.floor(Math.random() * 28) + 1).toISOString().split('T')[0],
      bio: `这是${firstName}${lastName}的个人简介`,
      timezone: 'Asia/Shanghai',
      language: 'zh-CN',
      passwordExpired: false,
      passwordChangeRequired: false,
      mustChangePasswordOnNextLogin: false,
      isExternal: false
    })
  }

  return users
}

const generateRandomRoles = (): Role[] => {
  return [
    {
      id: generateId(),
      name: 'Admin',
      displayName: '管理员',
      description: '系统管理员角色，拥有所有权限',
      isStatic: true,
      isDefault: false,
      isActive: true,
      creationTime: new Date().toISOString(),
      permissions: ['*']
    },
    {
      id: generateId(),
      name: 'User',
      displayName: '普通用户',
      description: '普通用户角色，拥有基本权限',
      isStatic: true,
      isDefault: true,
      isActive: true,
      creationTime: new Date().toISOString(),
      permissions: ['Identity.Users.Read', 'Identity.Roles.Read']
    },
    {
      id: generateId(),
      name: 'Manager',
      displayName: '管理者',
      description: '部门管理者角色',
      isStatic: false,
      isDefault: false,
      isActive: true,
      creationTime: new Date().toISOString(),
      permissions: ['Identity.Users.Read', 'Identity.Users.Update', 'Identity.Roles.Read']
    }
  ]
}

const generateRandomPermissions = (): Permission[] => {
  const permissions: Permission[] = []

  // 租户管理权限
  const tenantPermissions = [
    'TenantManagement.Tenants.Create',
    'TenantManagement.Tenants.Update',
    'TenantManagement.Tenants.Delete',
    'TenantManagement.Tenants.ManagePermissions',
    'TenantManagement.Features.Manage',
    'TenantManagement.Settings.Manage'
  ]

  // 用户管理权限
  const userPermissions = [
    'Identity.Users.Create',
    'Identity.Users.Update',
    'Identity.Users.Delete',
    'Identity.Users.ManagePermissions',
    'Identity.Users.ManageRoles',
    'Identity.Users.ChangePassword',
    'Identity.Users.ManageTwoFactor',
    'Identity.Users.ManageSessions'
  ]

  // 角色管理权限
  const rolePermissions = [
    'Identity.Roles.Create',
    'Identity.Roles.Update',
    'Identity.Roles.Delete',
    'Identity.Roles.ManagePermissions'
  ]

  const allPermissions = [...tenantPermissions, ...userPermissions, ...rolePermissions]

  allPermissions.forEach(permission => {
    const parts = permission.split('.')
    permissions.push({
      name: permission,
      displayName: parts[parts.length - 1],
      description: `${parts[0]} - ${parts[1]} - ${parts[2]}`,
      groupName: parts[0],
      parentName: parts.length > 3 ? parts.slice(0, -1).join('.') : null,
      isGranted: Math.random() > 0.3,
      isStatic: ['Identity.Users.Read', 'Identity.Roles.Read'].includes(permission)
    })
  })

  return permissions
}

// Mock数据存储
let mockTenants = generateRandomTenants(25)
let mockUsers = generateRandomUsers(100)
let mockRoles = generateRandomRoles()
let mockPermissions = generateRandomPermissions()

export class MockService {
  // 租户管理
  static async getTenantList(params: any = {}) {
    await delay()

    let filteredTenants = [...mockTenants]

    if (params.filter) {
      filteredTenants = filteredTenants.filter(tenant =>
        tenant.name.toLowerCase().includes(params.filter.toLowerCase()) ||
        tenant.code.toLowerCase().includes(params.filter.toLowerCase())
      )
    }

    if (params.isActive !== undefined) {
      filteredTenants = filteredTenants.filter(tenant => tenant.isActive === params.isActive)
    }

    if (params.isDefault !== undefined) {
      filteredTenants = filteredTenants.filter(tenant => tenant.isDefault === params.isDefault)
    }

    // 分页
    const skipCount = params.skipCount || 0
    const maxResultCount = params.maxResultCount || 20
    const items = filteredTenants.slice(skipCount, skipCount + maxResultCount)

    return {
      items,
      totalCount: filteredTenants.length
    }
  }

  static async createTenant(request: any) {
    await delay()

    const newTenant: Tenant = {
      id: generateId(),
      name: request.name,
      code: request.code,
      displayName: request.name,
      description: request.description || '',
      isActive: true,
      isDefault: false,
      adminEmailAddress: request.adminEmailAddress,
      databaseType: request.databaseType,
      connectionString: request.connectionString,
      enabledFeatures: request.enabledFeatures || [],
      maxUsers: request.maxUsers || 100,
      maxStorageGB: request.maxStorageGB || 10,
      maxApiCallsPerDay: request.maxApiCallsPerDay || 10000,
      keycloakRealm: request.keycloakRealm || '',
      keycloakRealmDisplayName: request.keycloakRealmDisplayName || '',
      keycloakTheme: request.keycloakTheme || 'matrix',
      keycloakSettings: request.keycloakSettings || [],
      timezone: request.timezone || 'UTC',
      customSettings: request.customSettings || [],
      creationTime: new Date().toISOString(),
      lastModificationTime: new Date().toISOString(),
      userCount: 1,
      logo: null
    }

    mockTenants.unshift(newTenant)
    return newTenant
  }

  static async updateTenant(id: string, request: any) {
    await delay()

    const index = mockTenants.findIndex(t => t.id === id)
    if (index === -1) {
      throw new Error('租户不存在')
    }

    mockTenants[index] = {
      ...mockTenants[index],
      ...request,
      lastModificationTime: new Date().toISOString()
    }

    return mockTenants[index]
  }

  static async deleteTenant(id: string) {
    await delay()

    const index = mockTenants.findIndex(t => t.id === id)
    if (index === -1) {
      throw new Error('租户不存在')
    }

    if (mockTenants[index].isDefault) {
      throw new Error('不能删除默认租户')
    }

    mockTenants.splice(index, 1)
  }

  static async getTenantStatistics() {
    await delay()

    return {
      totalTenants: mockTenants.length,
      activeTenants: mockTenants.filter(t => t.isActive).length,
      inactiveTenants: mockTenants.filter(t => !t.isActive).length,
      totalUsers: mockUsers.length,
      newTenantsThisMonth: 3,
      activeTenantsGrowth: 5.2
    }
  }

  // 用户管理
  static async getUserList(params: any = {}) {
    await delay()

    let filteredUsers = [...mockUsers]

    if (params.filter) {
      filteredUsers = filteredUsers.filter(user =>
        user.userName.toLowerCase().includes(params.filter.toLowerCase()) ||
        user.email.toLowerCase().includes(params.filter.toLowerCase()) ||
        `${user.name}${user.surname}`.toLowerCase().includes(params.filter.toLowerCase())
      )
    }

    if (params.isActive !== undefined) {
      filteredUsers = filteredUsers.filter(user => user.isActive === params.isActive)
    }

    // 分页
    const skipCount = params.skipCount || 0
    const maxResultCount = params.maxResultCount || 20
    const items = filteredUsers.slice(skipCount, skipCount + maxResultCount)

    return {
      items,
      totalCount: filteredUsers.length
    }
  }

  static async createUser(request: any) {
    await delay()

    const newUser: User = {
      id: generateId(),
      userName: request.userName,
      name: request.name,
      surname: request.surname,
      email: request.email,
      phoneNumber: request.phoneNumber || null,
      isActive: true,
      lockoutEnabled: true,
      lockoutEnd: null,
      twoFactorEnabled: false,
      lastLoginTime: null,
      creationTime: new Date().toISOString(),
      lastModificationTime: new Date().toISOString(),
      roleNames: request.roleNames || ['User'],
      grantedPermissions: ['Identity.Users.Read', 'Identity.Roles.Read'],
      tenantId: request.tenantId || null,
      tenantName: request.tenantId ? '示例租户' : null,
      avatar: request.avatar || null,
      gender: request.gender || 'male',
      birthDate: request.birthDate || null,
      bio: request.bio || '',
      timezone: request.timezone || 'Asia/Shanghai',
      language: request.language || 'zh-CN',
      passwordExpired: false,
      passwordChangeRequired: false,
      mustChangePasswordOnNextLogin: false,
      isExternal: false
    }

    mockUsers.unshift(newUser)
    return newUser
  }

  static async updateUser(id: string, request: any) {
    await delay()

    const index = mockUsers.findIndex(u => u.id === id)
    if (index === -1) {
      throw new Error('用户不存在')
    }

    mockUsers[index] = {
      ...mockUsers[index],
      ...request,
      lastModificationTime: new Date().toISOString()
    }

    return mockUsers[index]
  }

  static async deleteUser(id: string) {
    await delay()

    const index = mockUsers.findIndex(u => u.id === id)
    if (index === -1) {
      throw new Error('用户不存在')
    }

    mockUsers.splice(index, 1)
  }

  static async getUserStatistics() {
    await delay()

    return {
      totalUsers: mockUsers.length,
      activeUsers: mockUsers.filter(u => u.isActive).length,
      lockedUsers: mockUsers.filter(u => u.lockoutEnabled).length,
      twoFactorEnabledUsers: mockUsers.filter(u => u.twoFactorEnabled).length,
      newUsersThisMonth: 8,
      activeUsersGrowth: 12.5
    }
  }

  static async getUserSessions(userId: string) {
    await delay()

    // 模拟用户会话数据
    const sessions = [
      {
        id: generateId(),
        deviceName: 'Chrome on Windows',
        deviceType: 'Desktop',
        browser: 'Chrome',
        browserVersion: '119.0.0.0',
        platform: 'Windows',
        ipAddress: '192.168.1.100',
        location: { city: '北京', country: '中国', region: '华北' },
        loginTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
        lastActivityTime: new Date(Date.now() - 10 * 60 * 1000).toISOString(),
        expiryTime: new Date(Date.now() + 22 * 60 * 60 * 1000).toISOString(),
        status: 'Active',
        isTwoFactorEnabled: true,
        isSecureConnection: true,
        isCurrentSession: true
      },
      {
        id: generateId(),
        deviceName: 'Safari on iPhone',
        deviceType: 'Mobile',
        browser: 'Safari',
        browserVersion: '17.0',
        platform: 'iOS',
        ipAddress: '192.168.1.101',
        location: { city: '上海', country: '中国', region: '华东' },
        loginTime: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
        lastActivityTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
        expiryTime: new Date(Date.now() + 23 * 60 * 60 * 1000).toISOString(),
        status: 'Active',
        isTwoFactorEnabled: false,
        isSecureConnection: true,
        isCurrentSession: false
      }
    ]

    return {
      items: sessions,
      totalCount: sessions.length
    }
  }

  static async revokeSession(userId: string, sessionId: string) {
    await delay()
    // 模拟撤销会话
    return true
  }

  // 角色管理
  static async getRoleList() {
    await delay()
    return {
      items: mockRoles,
      totalCount: mockRoles.length
    }
  }

  static async getPermissionList() {
    await delay()
    return {
      items: mockPermissions,
      totalCount: mockPermissions.length
    }
  }

  // 批量操作
  static async bulkOperation(request: any) {
    await delay()

    const { operation, itemIds } = request
    const successCount = itemIds.length
    const failureCount = 0

    return {
      successCount,
      failureCount,
      operation
    }
  }

  // 导入导出
  static async exportTenants(request: any) {
    await delay(2000) // 模拟较长的导出时间

    // 模拟返回一个Blob
    const csvContent = mockTenants.map(tenant =>
      `${tenant.name},${tenant.code},${tenant.isActive ? 'Active' : 'Inactive'}`
    ).join('\n')

    const blob = new Blob([csvContent], { type: 'text/csv' })
    return blob
  }

  static async exportUsers(request: any) {
    await delay(2000)

    const csvContent = mockUsers.map(user =>
      `${user.userName},${user.email},${user.isActive ? 'Active' : 'Inactive'}`
    ).join('\n')

    const blob = new Blob([csvContent], { type: 'text/csv' })
    return blob
  }

  // 健康检查
  static async performTenantHealthCheck(tenantId: string) {
    await delay()

    return {
      status: 'Healthy',
      checks: [
        { name: 'Database', status: 'Healthy', responseTime: 45 },
        { name: 'Keycloak', status: 'Healthy', responseTime: 120 },
        { name: 'FileStorage', status: 'Healthy', responseTime: 32 }
      ],
      responseTime: 65
    }
  }

  // Keycloak同步
  static async syncKeycloakUsers(tenantId: string) {
    await delay(3000) // 模拟同步时间

    return {
      syncedCount: Math.floor(Math.random() * 50) + 10,
      failedCount: Math.floor(Math.random() * 3),
      totalProcessed: Math.floor(Math.random() * 53) + 13
    }
  }
}

// 判断是否启用Mock服务
export const useMockService = import.meta.env.VITE_ENABLE_MOCK === 'true'

export default MockService